
//
//  StatusPhotosView.m
//  Weibo
//
//  Created by Anasue on 9/18/15.
//  Copyright (c) 2015 Anasue. All rights reserved.
//

#define MaxPhotosCount 9
#define StatusPhotoW 70
#define StatusPhotoH StatusPhotoW
#define StatusPhotoMargin 10
#define StatusPhotosMaxCols(count) ((count ==4)?2:3)

#import "StatusPhotosView.h"
#import "StatusPhotoView.h"
#import "Photo.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

@implementation StatusPhotosView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        [self setupPhotoView];
    }
    return self;
}

- (void)setupPhotoView
{
    for (int i = 0; i < MaxPhotosCount; i ++) {
        StatusPhotoView *photoView = [[StatusPhotoView alloc]init];
        photoView.tag = i;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]init];
        [gesture addTarget:self action:@selector(tapPhoto:)];
        [photoView addGestureRecognizer:gesture];
        [self addSubview:photoView];
    }
}

- (void)tapPhoto:(UITapGestureRecognizer *)gesture
{
    //创建浏览器
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc]init];
    //创建图片数组
    NSMutableArray *photos = [NSMutableArray array];
    //将photoView的图片放进photos
    for (int i = 0; i < self.pic_urls.count; i ++) {
        Photo *pic = self.pic_urls[i];
        MJPhoto *photo = [[MJPhoto alloc]init];
        photo.srcImageView = self.subviews[i];
        photo.url = [NSURL URLWithString:pic.bmiddle_pic];
        [photos addObject:photo];
    }
    //设置默认显示的图片索引
    browser.currentPhotoIndex = gesture.view.tag;
    
    //将图片数组添加进浏览器的图片中
    browser.photos = photos;
    [browser show];
}

- (void)setPic_urls:(NSArray *)pic_urls
{
    _pic_urls = pic_urls;
    for (int i = 0; i < MaxPhotosCount; i ++) {
        StatusPhotoView *photoView = self.subviews[i];
        if (i < pic_urls.count) {
            photoView.photo = pic_urls[i];
            photoView.hidden = NO;
        }else{
            photoView.hidden = YES;
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    NSInteger count = self.pic_urls.count;
    int maxCols = StatusPhotosMaxCols(count);
    for (int i = 0; i < MaxPhotosCount; i++) {
        int col = i % maxCols;
        int row = i / maxCols;
        StatusPhotoView *photoView = self.subviews[i];
        photoView.width = StatusPhotoW;
        photoView.height = StatusPhotoH;
        photoView.y = row * (StatusPhotoH + StatusPhotoMargin);
        photoView.x = col * (StatusPhotoW + StatusPhotoMargin);
    }
}

+ (CGSize)sizeWithPhotosCount:(int)count
{
    int maxCols = StatusPhotosMaxCols(count);
    int totalCols = count >=maxCols ? maxCols : count;
    int totalRows = (count + maxCols -1)/maxCols;
    CGFloat photosH = totalRows * StatusPhotoH + (totalRows - 1) * StatusPhotoMargin;
    CGFloat photosW = totalCols * StatusPhotoW +(totalCols - 1) * StatusPhotoMargin;
    return CGSizeMake(photosW, photosH);
}



@end
